package user

import (
	"github.com/gin-gonic/gin"
	"shejiao/base"
	user22 "shejiao/common/model/user"
	user2 "shejiao/common/service/user"
	common2 "shejiao/pkg/common"
	"shejiao/pkg/util"
	"time"
)

var User = new(user)

type user struct{}

// @summary 获取个人信息
// @tags 授权接口
// @Description 根据用户ID获取用户信息
// @ID get-user-info
// @Accept json
// @Produce json
// @Param token header string true "认证token"
// @Param   user_id  query    int  true  "用户ID"
// @Router /api/user/info [post]
func (user) Info(c *gin.Context) {
	var req struct {
		UserId int64 `json:"user_id"`
	}

	err := c.ShouldBind(&req)
	if err != nil {
		common2.Response.Error(c, "用户ID不存在", gin.H{"err": err.Error()})
		return
	}

	ui := user2.UserService.Info(req.UserId)
	if ui.Id == 0 {
		common2.Response.Error(c, "无法查询到用户", gin.H{})
		return
	}

	common2.Response.Success(c, gin.H{"user_info": ui})

}

// @summary 匹配接口
// @tags 授权接口
// @Description 根据用户ID获取用户信息
// @Accept json
// @Produce json
// @Param token header string true "认证token"
// @Param   match_type  query    int  true  "call语音 chat聊天"
// @Param   region  query    string  true  "匹配区域"
// @Router /api/user/room/match [post]
func (u user) Match(c *gin.Context) {
	var req struct {
		MatchType string `json:"match_type"` // call chat
		Region    string `json:"region"`     // 匹配区域
	}
	err := c.ShouldBind(&req)
	if err != nil {
		common2.Response.Error(c, "匹配类型有误", gin.H{})
		return
	}
	RoleId := util.GetRoleId(c)

	now := time.Now()
	y, m, d := int64(now.Year()), int64(now.Month()), int64(now.Day())
	umr := user2.UserMatchRecorderService.Get(RoleId, y, m, d)

	// 开始匹配 搜索在线人数
	if req.MatchType == "call" {
		if umr.UsableCallCnt <= 0 {
			common2.Response.Error(c, "拨打次数不足", gin.H{})
			return
		}
		user2.UserMatchRecorderService.DelCall(RoleId, y, m, d)
	}

	if req.MatchType == "chat" {
		if umr.UsableCallCnt <= 0 {
			common2.Response.Error(c, "聊天次数不足", gin.H{})
			return
		}
		user2.UserMatchRecorderService.DelChat(RoleId, y, m, d)
	}

	// 开始匹配
	roleId, err := user2.UserService.Match(RoleId, req.MatchType, req.Region)
	if err != nil {
		common2.Response.Error(c, "匹配失败", gin.H{"err": err.Error()})
		return
	}

	common2.Response.Success(c, gin.H{"user_id": roleId})

}

// @summary ping在线
// @tags 授权接口
// @Description 保持在线ping
// @Accept json
// @Produce json
// @Param token header string true "认证token"
// @Router /api/user/ping [post]
func (u user) Ping(c *gin.Context) {
	roleId := util.GetRoleId(c)
	base.Mysql.Model(&user22.UserInfo{}).Where("id = ?", roleId).Update("ping_at", time.Now().Unix())
	common2.Response.Success(c, gin.H{})
}
